package com.hmdp.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.hmdp.utils.SystemConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.SystemConstants.CACHE_SHOP_LIST_KEY;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result querySortList() {
        //1.从redis查询商铺缓存
        String Key = CACHE_SHOP_LIST_KEY;
        Long size = redisTemplate.opsForList().size(Key);
        List<ShopType> shopList = redisTemplate.opsForList().range(Key, 0, -1);
        //2.判断是否存在
        if (shopList.size()!=0){
            //3.存在，直接返回
            List<ShopType> arr = new ArrayList<>();
            for (int i = 0;i < size;i++){
                ShopType shopType = shopList.get(i);
                arr.add(shopType);
            }
            return Result.ok(arr);
        }
        //4.不存在，从数据库查询，再保存到redis
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        redisTemplate.opsForList().rightPushAll(Key,shopTypeList);

        //7.返回信息
        return Result.ok(shopTypeList);
    }
}
